package com.passer.network.wlan;

import com.passer.network.constant.WindowsWlanCmd;
import com.passer.network.constant.WlanProperties;
import com.passer.toolbox.common.core.util.CmdUtils;
import com.passer.toolbox.common.file.util.WriteFileUtils;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

@Slf4j
@Getter
public class WlanProfileTemplate {

    private final WlanProperties wlanProperties;

    private final String wlanProfileTemplate;

    public WlanProfileTemplate() {
        this.wlanProperties = new WlanProperties();
        String line;
        StringBuilder stringBuilder = new StringBuilder();
        try(RandomAccessFile accessFile = new RandomAccessFile(new File("", wlanProperties.getWlanProfileTemplate()), "r")) {
            while((line = accessFile.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        this.wlanProfileTemplate = stringBuilder.toString();
    }

    public boolean addWlanProfile(String ssid, String password) {
        File file = new File(wlanProperties.getWlanFilePath(), ssid + ".xml");
        try {
            WriteFileUtils.writeFileByString(file.getAbsolutePath(), this.wlanProfileTemplate);
        } catch (IOException e) {
            log.error("生成{}的profile文件失败：{}", ssid, e.toString());
            return false;
        }
        String cmd = String.format(WindowsWlanCmd.CMD_ADD_WLAN, wlanProperties.getWlanFilePath());
        String runCmdResult;
        try {
            runCmdResult = CmdUtils.runCmd(cmd);
        } catch (IOException e) {
            log.error("{}命令执行失败失败：{}", cmd, e.toString());
            return false;
        }
        return true;
    }
}
